package com.example.permissionservice.interceptor;

import com.example.permissionservice.config.JwtConfig;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {
    private final JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String path = request.getRequestURI();
        // 可根据需要放行部分接口
        if (path.contains("/login") || path.contains("/register") || path.contains("/user-role") || path.contains("/bind-default-role")) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        token = token.substring(7);
        try {
            if (!jwtConfig.validateToken(token)) {
                System.out.println("[JwtInterceptor] Token validate failed: " + token);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            Claims claims = jwtConfig.parseToken(token);
            request.setAttribute("userId", claims.get("userId"));
            request.setAttribute("username", claims.get("username"));
            request.setAttribute("roleCode", claims.get("roleCode"));
        } catch (Exception e) {
            System.out.println("[JwtInterceptor] Exception: " + e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }
}
